import Layout from '@/views/layout/Layout.vue';
import { createRouter, createWebHistory } from 'vue-router';
import { useUserStore } from '@/stores/userStore';

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue')
  },
  {
    path: '/',
    component: Layout,
    redirect: '/student',
    children: [
      {
        path: 'student',
        name: 'Student',
        component: () => import('@/views/Student.vue')
      },
      {
        path: 'teacher',
        name: 'Teacher',
        component: () => import('@/views/Teacher.vue')
      },
      {
        path: 'class',
        name: 'Class',
        component: () => import('@/views/Class.vue')
      }
    ]
  }
];

const router = createRouter({
  history: createWebHistory(),
  routes
});

// 路由守卫
router.beforeEach((to, from, next) => {

  // 获取 token
  const userStore = useUserStore()
  const token = userStore.token
  
  if (to.path === '/login') {
    next();
  } else {
    if (!token) {
      next('/login');
    } else {
      next();
    }
  }
});

export default router;
